<template>
  <div>
    <!-- 编辑角色的表单，平时隐藏 -->
    <el-dialog title="添加角色" :visible.sync="isEditFormVisible" width="50%">
      <span>
        <el-form
          :model="editForm"
          :rules="addFormRules /*编辑和添加角色的规则一样*/"
          ref="editFormRef"
          label-width="100px"
        >
          <el-form-item label="角色id">
            <el-input v-model="editForm.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限表单 平时隐藏 -->
    <el-dialog
      title="分配权限"
      @close="defaultKeys = []"
      :visible.sync="isSetRightsVisible"
      width="40%"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="rightsListProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defaultKeys"
        ref="rightTreeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isSetRightsVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRight()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色的表单，平时隐藏 -->
    <el-dialog title="添加角色" :visible.sync="isAddFormVisible" width="50%">
      <span>
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 添加角色的按钮 -->
      <el-row type="flex" justify="">
        <el-col :span="3">
          <el-button type="primary" @click="isAddFormVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 权限列表数据 表格 -->
      <el-table :data="rolesList" stripe style="width: 100%" border>
        <!-- 展开行 -->
        <el-table-column type="expand" label="">
          <template slot-scope="scope">
            <el-row
              class="quanxian1"
              type="flex"
              v-for="item1 in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}</el-tag
                ><i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row
                  class="quanxian2"
                  type="flex"
                  v-for="item2 in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >
                      {{ item2.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      class="quanxian3"
                      @close="removeRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="toEditForm(scope.row)"
              >编辑</el-button
            >

            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteTheRole(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightsList(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //存放角色列表的数组
      rolesList: [],
      //存放权限列表的数组 type=tree
      rightsList: [],
      //控制添加角色表单显示与否的变量 默认隐藏
      isAddFormVisible: false,
      //存放添加用户表单的对象
      addForm: {
        roleName: "",
        roleDesc: "",
      },
      //存放添加角色表单验证规则的对象
      addFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
      },
      //控制编辑角色表单显示与否的变量 默认隐藏
      isEditFormVisible: false,
      //存放添加用户表单的对象
      editForm: {
        id: "",
        roleName: "",
        roleDesc: "",
      },
      //控制分配权限的对话框显示与否
      isSetRightsVisible: false,
      //存放 树形控件规则的对象
      rightsListProps: {
        children: "children",
        label: "authName",
      },
      //树形控件默认勾选的key
      defaultKeys: [],
      //保存正在分配权限的角色的id
      nowHandleRole: {},
    };
  },
  methods: {
    //更新角色列表的函数
    async getRolesList() {
      //发送请求获取角色列表数据;
      const { data: res } = await this.$http.get(`roles`);
      console.log(res);
      if (res.meta.status == 200) {
        //获取权限列表成功
        this.rolesList = res.data;
      } else {
        this.$message.error("获取角色列表失败");
      }
    },
    //更新权限列表的函数  并把分配权限对话框变成显示
    async showSetRightsList(val) {
      //保存正在分配角色权限的角色的id
      this.nowHandleRole = val;
      // console.log(val.id);
      const { data: res } = await this.$http.get(`rights/tree`);
      console.log(res);
      if (res.meta.status == 200) {
        //获取权限列表成功
        this.rightsList = res.data;
        this.getRightIdToArray(val, this.defaultKeys);
        this.isSetRightsVisible = true;
      } else {
        this.$message.error("获取权限列表失败");
      }
    },
    //删除权限功能  权限被点击删除的时候触发
    async removeRightById(role, rightId) {
      //提示用户
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //用户点击了删除
          //发送删除请求
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          console.log(res);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          //重新获取角色列表  这里不建议获取整一个角色列表，会重置页面
          //this.getRolesList();
          role.children = res.data;
        })
        .catch(() => {
          //用户点击取消
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //提交添加角色表单请求
    async submitAddForm() {
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid);
        if (valid == true) {
          //表单验证通过了，这时候我们再发送请求
          const { data: res } = await this.$http.post(`roles`, this.addForm);
          if (res.meta.status == 201) {
            //添加角色成功
            this.$message.success("添加成功");
            //把添加角色的对话框隐藏
            this.isAddFormVisible = false;
            //添加成功后需要重新获取角色列表
            this.getRolesList();
          } else {
            //添加角色失败。
            this.$message.error("添加失败,请检查网络");
          }
        }
      });
    },
    //删除角色
    async deleteTheRole(roleId) {
      // console.log(roleId);
      //成功拿到所要删除的角色的id
      // 发送请求
      const { data: res } = await this.$http.delete(`roles/${roleId}`);
      if (res.meta.status == 200) {
        //删除成功
        this.$message.success("删除成功");
        //删除成功后重新获取角色列表
        this.getRolesList();
      } else {
        //删除失败
        this.$message.error("删除失败，请检查网络");
      }
    },
    //获取正要编辑的角色的id 显示其信息在页面中
    async toEditForm(role) {
      console.log(role);
      //将用户信息显示在表单中
      this.editForm.id = role.id;
      this.editForm.roleName = role.roleName;
      this.editForm.roleDesc = role.roleDesc;
      //显示编辑角色对话框
      this.isEditFormVisible = true;
    },
    //提交编辑角色表单的请求
    async submitEditForm() {
      this.$refs.editFormRef.validate(async (valid) => {
        console.log(valid);
        if (valid == true) {
          //表单验证通过了，这时候我们再发送请求
          const { data: res } = await this.$http.put(
            `roles/${this.editForm.id}`,
            this.editForm
          );
          if (res.meta.status == 200) {
            //修改角色成功
            this.$message.success("修改成功");
            //把修改角色的对话框隐藏
            this.isEditFormVisible = false;
            //修改成功后需要重新获取角色列表
            this.getRolesList();
          } else {
            //修改角色失败。
            this.$message.error("修改失败,请检查网络");
          }
        }
      });
    },
    //通过一个递归函数，将所有三级权限的id存放到数组中 给树状控件默认选中
    getRightIdToArray(node, array) {
      //参数一为树节点，参数二为放默认选中id的数组
      if (!node.children) {
        //如果 节点没有children属性，说明已经是最后一级节点了
        array.push(node.id);
        return;
      } else {
        //这个树节点不是最后一级节点
        //将这个节点的儿子节点调用这个函数 进行递归
        node.children.forEach((element) => {
          this.getRightIdToArray(element, array);
        });
      }
    },
    //角色授权函数 发送请求
    async submitRight() {
      // console.log(...this.$refs.rightTreeRef.getCheckedKeys());
      // console.log(...this.$refs.rightTreeRef.getHalfCheckedKeys());
      const keys = [
        ...this.$refs.rightTreeRef.getCheckedKeys(),
        ...this.$refs.rightTreeRef.getHalfCheckedKeys(),
      ];
      const keysStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.nowHandleRole.id}/rights`,
        {
          rids: keysStr,
        }
      );
      if (res.meta.status == 200) {
        //更新权限成功
        this.$message.success("更新权限成功");
        //更新成功后应该把默认选中换一下
        this.getRolesList(); //我们直接重新获取角色列表
      } else {
        this.$message.error("更新权限失败");
      }
    },
  },
  //vue一被创建就获取表单数据
  created() {
    //调用获取角色列表函数
    this.getRolesList();
  },
  watch: {
    //监听添加角色表单的隐藏与否
    isAddFormVisible: function (newVal, oldVal) {
      //隐藏了 就重置表单
      if (newVal == false && oldVal == true) {
        this.$refs.addFormRef.resetFields();
      }
    },
    //监听编辑角色表单的隐藏与否
    isEditFormVisible: function (newVal, oldVal) {
      //隐藏了 就重置表单
      if (newVal == false && oldVal == true) {
        //用定时器延时个200ms吧  这样会防止重置表单比关闭对话框先完成
        setTimeout(() => {
          //用箭头函数 this指针不改变
          this.$refs.editFormRef.resetFields();
        }, 200);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.quanxian1 {
  padding-bottom: 10px;
  margin: 7px;
  border-bottom: 1px solid rgb(235, 238, 245);
}

.quanxian2 {
  padding-bottom: 10px;
  margin: 7px;
}

.quanxian3 {
  padding-bottom: 10px;
  margin: 7px;
}

.el-row {
  align-items: center;
}
</style>